use crate::shared::china_citizen_id;

use stdx::iter::IteratorExt;

#[must_use]
pub fn check_id_card(id_card_no: &str) -> String {
    let result = if id_card_no.len() == 18 {
        china_citizen_id::parse_v2(id_card_no)
    } else if id_card_no.len() == 15 {
        china_citizen_id::parse_v1(id_card_no)
    } else {
        return "身份证号码错误".to_owned();
    };

    let Ok(parsed) = result else {
        return "身份证号码错误".to_owned();
    };

    let sex = match parsed.sex() {
        china_citizen_id::Sex::Male => "男",
        china_citizen_id::Sex::Female => "女",
    };

    let (year, month, day) = parsed.birthday_ymd();
    let region = fmt_region(parsed.region());

    format!("身份证号码正确,{sex},{year}年{month:02}月{day:02}日,{region}")
}

fn fmt_region(region: &china_citizen_id::Region) -> String {
    if region.province.is_none() && region.city.is_none() && region.district.is_none() {
        return "未知地区".to_owned();
    }

    let mut parts = ["", "", ""];

    match region.province {
        Some(province @ ("北京市" | "天津市" | "上海市" | "重庆市")) => {
            parts[0] = province;
            parts[1] = "市辖区";
            parts[2] = region.district.unwrap();
        }
        Some(province) => parts[0] = province,
        None => {}
    }

    if let Some(city) = region.city {
        parts[1] = city;
    }

    if let Some(district) = region.district {
        parts[2] = district;
    }

    parts.into_iter().filter(|s| !s.is_empty()).join_("-")
}
